/*
 * Copyright (c) China Telecom Cloud Technology Co., Ltd. 2024-2025. All rights reserved.
 */
#ifndef THREE_FS_STRATEGY_H
#define THREE_FS_STRATEGY_H

#include "../../3FS/src/lib/api/hf3fs_usrbio.h"
#include "FsStrategy.h"
#include <memory>
#include <mutex>

#define INDEX_MOD 4096

class ThreeFsStartegy final : public FsStrategy {
  public:
    ThreeFsStartegy(std::string mountPath, std::string path, void *addr)
        : FsStrategy(mountPath, path, addr) {}

    ~ThreeFsStartegy();

    const std::string fsPrefix = "kvcache_";

    int32_t get(const std::string &objId, const Segment &segment,
                const uint64_t srcOffset, const uint64_t dstOffset,
                const uint64_t length) noexcept override;

    int32_t put(const std::string &objId, const Segment &segment,
                const uint64_t srcOffset, const uint64_t dstOffset,
                const uint64_t length) noexcept override;

    int32_t remove(const std::string &objId) noexcept override;

    bool isExist(const std::string &objId) noexcept override;

    int32_t createIov() noexcept;

    hf3fs_iov *getIov() noexcept;

  private:
    int32_t usrbioReadWrite(const Segment *segment, const uint64_t srcOffset,
                            const std::string &objId, const uint64_t tgtFileOff,
                            const uint64_t ioSize, const bool read);

    // singleton for hf3fs_ior
    static thread_local inline std::unique_ptr<struct hf3fs_ior> readIor;
    static thread_local inline std::unique_ptr<struct hf3fs_ior> writeIor;
    static thread_local inline std::mutex readIorMutex;
    static thread_local inline std::mutex writeIorMutex;

    static hf3fs_ior *getReadIor(std::string fsMountPath);
    static hf3fs_ior *getWriteIor(std::string fsMountPath);

    // iov
    hf3fs_iov iov;
    bool inited = false;
};

#endif